<template>
  <view
    class="x-touch"
    @click="handleClick"
    @touchstart="touchStart"
    @touchmove="touchMove"
    @touchend="touchEnd"
    @touchcancel="touchCancel"
  >
    <slot></slot>
  </view>
</template>

<script>
export default {
  name: 'XTouch',
  components: {},
  props: {
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      touchStartX: 0, // 触摸时的原点
      touchStartY: 0, // 触摸时的原点
      left: 0,
      top: 0
    };
  },
  computed: {},
  watch: {},
  created() {

  },
  methods: {
    // 触摸开始事件
    touchStart(e) {
      // console.log(1, this.disabled);
      if (this.disabled) return;
      const { pageX, pageY } = e.changedTouches[0];
      this.touchStartX = pageX; // 获取触摸时的原点
      this.touchStartY = pageY; // 获取触摸时的原点
    },
    // 手指触摸后移动
    touchMove(e) {
      // console.log(2);
      if (this.disabled) return;
      const { pageX, pageY } = e.changedTouches[0];
      this.left = pageX - this.touchStartX;
      this.top = pageY - this.touchStartY;
      this.$emit('move', {
        left: parseInt(this.left),
        top: parseInt(this.top)
      });
    },
    // 触摸结束事件
    touchEnd(e) {
      // console.log(3);
      if (this.disabled) return;
      this.touchStartX -= e.changedTouches[0].pageX;
      this.touchStartY -= e.changedTouches[0].pageY;

      if (Math.abs(this.touchStartX) > Math.abs(this.touchStartY)) {
        if (Math.abs(this.touchStartX) > 30) {
          if (this.touchStartX > 0) {
            this.$emit('change', 'right');
            // console.log("右滑页面")
          } else {
            this.$emit('change', 'left');
            // console.log("左滑页面")
          }
        } else {
          this.$emit('end');
        }
      } else {
        if (Math.abs(this.touchStartY) > 30) {
          if (this.touchStartY > 0) {
            this.$emit('change', 'top');
            // console.log("上滑页面")
          } else {
            this.$emit('change', 'bottom');
            // console.log("下滑页面")
          }
        } else {
          this.$emit('end');
        }
      }
    },
    // 手指触摸动作被打断，如来电提醒，弹窗
    touchCancel() {
      this.$emit('end');
    },
    handleClick() {
      this.$emit('click');
    }
  }
};
</script>

<style>

</style>
